package development;

import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.ResourceRms;
import state.bean.GameRect;
import state.component.Event;
import state.component.EventListener;
import state.font.FontManager;
import state.font.ImageText;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.array.StringArray;
import development.game.FrmAilaTrieuPhuOff;
import development.game.FrmDaoVangOffline;
import development.group.FrmGroupFriendAndTop;
import development.group.FrmGroupMenu;
import development.listener.DownloadResourceListener;
import development.socket.SocketClientUtil;

public class FrmMenuGame extends GameForm {
  private int HOZ_DISTANCE;
  private int VER_DISTANCE;
  private int DX;
  private int DY;
  private int ITEM_WIDTH;
  private int ITEM_PER_ROW;

  private GameImage[] itemsImages;
  private ImageText text8;

  private int numberOfItem;

  private String[] menuText;
  private int countRow;
  private int currentSelectedIndex;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmMenuGame();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    numberOfItem = 6;
    currentSelectedIndex = 0;

    if (getGameOff(Global.currentGame.getId()) != null) {
      menuText = new String[]{"Vào phòng", "Chơi Offline", "Tự động tìm bàn", "Mời chơi", "Danh sách cao thủ", "Hướng dẫn"};
      itemsImages = new GameImage[numberOfItem];
      itemsImages[0] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Vao-phong.png");
      itemsImages[1] = itemsImages[0];
      itemsImages[2] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Tu-tim-phong.png");
      itemsImages[3] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_moi-ngau-nhien.png");
      itemsImages[4] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Danh-sach.png");
      itemsImages[5] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Huong-dan.png");
    } else {
      menuText = new String[]{"Vào phòng", "Tự động tìm bàn", "Mời chơi", "Danh sách cao thủ", "Danh sách đại gia", "Hướng dẫn"};
      itemsImages = new GameImage[numberOfItem];
      itemsImages[0] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Vao-phong.png");
      itemsImages[1] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Tu-tim-phong.png");
      itemsImages[2] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_moi-ngau-nhien.png");
      itemsImages[3] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Danh-sach.png");
      itemsImages[4] = itemsImages[3];
      itemsImages[5] = ImageUtil.getImage(Constants.GAME_MENU_ICON_CATEGORY, "icon_Huong-dan.png");
    }

    if (Global.currentGame.getId().equals("daovang")) {
      itemsImages[5] = itemsImages[0];
    }

    if (Constants.IS_240x320_SCREEN) {
      HOZ_DISTANCE = 0;
      VER_DISTANCE = 23;
      DX = 50;
      DY = 89;
      ITEM_WIDTH = 142;
      ITEM_PER_ROW = 1;
    } else {
      HOZ_DISTANCE = 5;
      VER_DISTANCE = 23;
      DX = 16;
      DY = 67;
      ITEM_WIDTH = 142;
      ITEM_PER_ROW = 2;
    }
    if (numberOfItem % ITEM_PER_ROW == 0) {
      countRow = numberOfItem / ITEM_PER_ROW;
    } else {
      countRow = numberOfItem / ITEM_PER_ROW + 1;
    }
    setSize((ITEM_WIDTH + HOZ_DISTANCE) * ITEM_PER_ROW + 1, countRow * VER_DISTANCE + 4);
    setPosition(DX, DY);
  }
  
  private GameForm getGameOff(String gameId) {
    if ("daovang".equals(gameId)) {
      return FrmDaoVangOffline.instance();
    }
    if ("duoihinhbatchu".equals(gameId)) {
      // TODO: disable DHBC off
//    	return FrmDuoiHinhBatChuOff.instance();
    }
    if ("ailatrieuphu".equals(gameId)) {
      return FrmAilaTrieuPhuOff.instance();
    }
    
    if ("audition".equals(gameId)) {
      // TODO: disable audition
//      FrmSelectSong.backForm = FrmGroupMenu.instance();
//      AuditionConstants.playMode = AuditionConstants.OFFLINE_MODE;
//      return FrmSelectSong.instance();
    }
    return null;
  }
  
  public void draw(Graphics g) {
    DrawUtils.setBottomBar(_manager, null, null, "Đóng");
    g.setColor(0x6B0101);
    g.fillRect(DX, DY, (ITEM_WIDTH + HOZ_DISTANCE) * ITEM_PER_ROW, countRow * VER_DISTANCE + 3);
    
    for (int i = 0; i < 6; i++) {
      int x = DX + i % ITEM_PER_ROW * (HOZ_DISTANCE + ITEM_WIDTH);
      int y = DY + i / ITEM_PER_ROW * VER_DISTANCE;
      if (currentSelectedIndex == i) {
        g.setColor(0x2E772E);
        g.fillRect(x + 2,y + 2, ITEM_WIDTH - 3, VER_DISTANCE);
        text8.drawString2(g, menuText[i], 0xDDFD52, x + 33, y + 5, GameConstants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, menuText[i], 0xF3DE34, x + 33, y + 5, GameConstants.TOP_LEFT_ANCHOR);
      }
      g.drawImage(itemsImages[i], x + 7, y + 4, Constants.TOP_LEFT_ANCHOR);
    }
    
    g.setColor(GameColor.YELLOW_CODE);
    g.drawRect(DX, DY, (ITEM_WIDTH + HOZ_DISTANCE) * ITEM_PER_ROW, countRow * VER_DISTANCE + 3);
  }
  
  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.UP:
      currentSelectedIndex = (currentSelectedIndex - ITEM_PER_ROW < 0) ? 0 : currentSelectedIndex - ITEM_PER_ROW;
      break;
    case Key.DOWN:
      currentSelectedIndex = (currentSelectedIndex + ITEM_PER_ROW > 5) ? 5 : currentSelectedIndex + ITEM_PER_ROW;
      break;
    case Key.RIGHT:
      currentSelectedIndex = (currentSelectedIndex + 1 > numberOfItem - 1) ? numberOfItem - 1 : currentSelectedIndex + 1;
      break;
    case Key.LEFT:
      currentSelectedIndex = (currentSelectedIndex - 1 < 0) ? 0 : currentSelectedIndex - 1;
      break;
    case Key.FIRE:
      processMenu(currentSelectedIndex);
      break;
    case Key.SOFT_RIGHT:
      Global.systemCanvas.hideAlert();
      break;
    }
  }
  
  public void pointerReleased(int x1, int y1) {
    if (contains(x1, y1)) {
      GameRect rect = new GameRect(0, 0, ITEM_WIDTH - 3, VER_DISTANCE);
      for (int i = 0; i < 6; i++) {
        rect._x = DX + i % ITEM_PER_ROW * (HOZ_DISTANCE + ITEM_WIDTH);
        rect._y = DY + i / ITEM_PER_ROW * VER_DISTANCE;
        
        if (rect.contains(x1, y1)) {
          currentSelectedIndex = i;
          processMenu(currentSelectedIndex);
          break;
        }
      }
    }
  }
  
  private void processMenu(int index) {
    // "Vào phòng", "Chơi Offline", "Tự động tìm bàn", "Mời người chơi", "Danh sách cao thủ", "Danh sách đại gia", "Hướng dẫn"
    String choosedMenuText = menuText[index];
    
    if ("Vào phòng".equals(choosedMenuText)) {
      checkToDownloadResource(FrmListRoom.instance());
      return;
    }
    if ("Chơi Offline".equals(choosedMenuText)) {
      GameForm gameOff = getGameOff(Global.currentGame.getId());
      if (gameOff != null) {
        SocketClientUtil.requestPlayGameOff();
        checkToDownloadResource(gameOff);
      }
      return;
    }
    if ("Tự động tìm bàn".equals(choosedMenuText)) {
      checkToDownloadResource(FrmDownloadResource.instance()).setOnDownloadDoneListener(new EventListener() {
        public void onActionPerform(Event event) {
          SocketClientUtil.autoFindTable();
        }
      });
      return;
    }
    if ("Mời chơi".equals(choosedMenuText)) {
      checkToDownloadResource(FrmListFreeUser.instance());
      return;
    }
    if ("Danh sách cao thủ".equals(choosedMenuText)) {
      checkToDownloadResource(FrmGroupFriendAndTop.instance());
      FrmGroupFriendAndTop.backForm = FrmGroupMenu.instance();
      FrmGroupFriendAndTop.setTab(2);
      return;
    }
    if ("Danh sách đại gia".equals(choosedMenuText)) {
      checkToDownloadResource(FrmGroupFriendAndTop.instance());
      FrmGroupFriendAndTop.backForm = FrmGroupMenu.instance();
      FrmGroupFriendAndTop.setTab(1);
      return;
    }
    if ("Hướng dẫn".equals(choosedMenuText)) {
      FrmChooseGame frmChooseGame = (FrmChooseGame) FrmChooseGame.instance();
      if (frmChooseGame.getGridMenu() != null) {
        String gameId = Constants.GAME_ID.get(frmChooseGame.getGridMenu().getCurrentSelectedIndex());
        Hashtable parameters = new Hashtable();
        parameters.put("helpId", gameId);
        Global.nextState(FrmGuide.instance(), parameters);
      }
      return;
    }
  }
  
  private DownloadResourceListener checkToDownloadResource(GameForm nextForm) {
    // Canculate the image to download
    String gameId = Global.currentGame.getId();
    Object gameResourceProfile = Global.resourceConfig.get(gameId);
    StringArray mandatoryProfile = null;
    if ((gameResourceProfile != null) && ("audition".equals(gameId) || "cotuong".equals(gameId) || "covua".equals(gameId) || "daovang".equals(gameId))) {
      StringArray gamecategoryProfile = (StringArray) gameResourceProfile;
      StringArray tmp = (StringArray) Global.resourceConfig.get(Constants.INIT_RESOURCE_PROFILE);
      mandatoryProfile = StringArray.create(gamecategoryProfile.len() + tmp.len());
      StringArray.arraycopy(gamecategoryProfile, 0, mandatoryProfile, 0, gamecategoryProfile.len());
      StringArray.arraycopy(tmp, 0, mandatoryProfile, gamecategoryProfile.len(), tmp.len());
    } else {
      mandatoryProfile = (StringArray) Global.resourceConfig.get(Constants.INIT_RESOURCE_PROFILE);
    }
    
    // Trim downloaded resource
    mandatoryProfile = trimAllDowloadedCategory(mandatoryProfile);
    
    // Start to download resource
    DownloadResourceListener downloadResourceListener = new DownloadResourceListener(mandatoryProfile);
    downloadResourceListener.nextForm = nextForm;
    Global.authenticateHandle.addListener(downloadResourceListener);
    GameGlobal.nextState(FrmDownloadResource.instance(), null);
    return downloadResourceListener;
  }
  
  private StringArray trimAllDowloadedCategory(StringArray categories) {
    int count = 0;
    for (int i = 0; i < categories.len(); i++) {
      if (categories.get(i) != null) {
        Hashtable resourceByCategory = (Hashtable) Global.resourceCategory.get(categories.get(i));
        if (resourceByCategory == null) {
          resourceByCategory = ResourceRms.loadMasterRecord(categories.get(i));
        }
        if (resourceByCategory == null) {
          count++;
        } else {
          categories.set(i, null);
        }
      }
    }
    
    StringArray result = StringArray.create(count);
    count = 0;
    for (int i = 0; i < categories.len(); i++) {
      if (categories.get(i) != null) {
        result.set(count, categories.get(i));
        count++;
      }
    }
    return result;
  }

  public void destroy() {
    itemsImages = null;
    text8 = null;
    menuText = null;
  }
}